package com.industrial.premu.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuAnalysisPolicyImple;
import com.industrial.premu.domain.PreMuPolicyAnisVo;
import com.industrial.premu.domain.PremuPioneerCounty;
import com.industrial.premu.domain.vo.PreMuAnalysisPolicyImpleUnExecVo;
import com.industrial.premu.mapper.PreMuAnalysisPolicyImpleMapper;
import com.industrial.premu.service.IPreMuAnalysisPolicyImpleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 差别化政策执行分析Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-30
 */
@Service
public class PreMuAnalysisPolicyImpleServiceImpl implements IPreMuAnalysisPolicyImpleService
{
    @Autowired
    private PreMuAnalysisPolicyImpleMapper preMuAnalysisPolicyImpleMapper;


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询差别化政策执行分析
     *
     * @param baseId 差别化政策执行分析主键
     * @return 差别化政策执行分析
     */
    @Override
    public PreMuAnalysisPolicyImple selectPreMuAnalysisPolicyImpleByBaseId(String baseId)
    {
        return preMuAnalysisPolicyImpleMapper.selectPreMuAnalysisPolicyImpleByBaseId(baseId);
    }

    /**
     * 查询差别化政策执行分析列表
     *
     * @param preMuAnalysisPolicyImple 差别化政策执行分析
     * @return 差别化政策执行分析
     */
    @Override
    public List<PreMuAnalysisPolicyImple> selectPreMuAnalysisPolicyImpleList(PreMuAnalysisPolicyImple preMuAnalysisPolicyImple)
    {
        List<PreMuAnalysisPolicyImple> preMuAnalysisPolicyImples = preMuAnalysisPolicyImpleMapper.selectPreMuAnalysisPolicyImpleList(preMuAnalysisPolicyImple);
        for(PreMuAnalysisPolicyImple temp : preMuAnalysisPolicyImples){
            if(StringUtils.isNotBlank(temp.getProvince())){
                String pN = redisTemplate.opsForValue().get("area:" + temp.getProvince());
                temp.setProvinceName(pN);
            }

            if(StringUtils.isNotBlank(temp.getCity())){
                String pN = redisTemplate.opsForValue().get("area:" + temp.getCity());
                temp.setCityName(pN);
            }

            if(StringUtils.isNotBlank(temp.getCounty())){
                String pN = redisTemplate.opsForValue().get("area:" + temp.getCounty());
                temp.setCountyName(pN);
            }
        }
        return preMuAnalysisPolicyImples;
    }

    /**
     * 新增差别化政策执行分析
     *
     * @param preMuAnalysisPolicyImple 差别化政策执行分析
     * @return 结果
     */
    @Override
    public int insertPreMuAnalysisPolicyImple(PreMuAnalysisPolicyImple preMuAnalysisPolicyImple)
    {
        return preMuAnalysisPolicyImpleMapper.insertPreMuAnalysisPolicyImple(preMuAnalysisPolicyImple);
    }

    /**
     * 修改差别化政策执行分析
     *
     * @param preMuAnalysisPolicyImple 差别化政策执行分析
     * @return 结果
     */
    @Override
    public int updatePreMuAnalysisPolicyImple(PreMuAnalysisPolicyImple preMuAnalysisPolicyImple)
    {
        return preMuAnalysisPolicyImpleMapper.updatePreMuAnalysisPolicyImple(preMuAnalysisPolicyImple);
    }

    /**
     * 批量删除差别化政策执行分析
     *
     * @param baseIds 需要删除的差别化政策执行分析主键
     * @return 结果
     */
    @Override
    public int deletePreMuAnalysisPolicyImpleByBaseIds(String[] baseIds)
    {
        return preMuAnalysisPolicyImpleMapper.deletePreMuAnalysisPolicyImpleByBaseIds(baseIds);
    }

    /**
     * 删除差别化政策执行分析信息
     *
     * @param baseId 差别化政策执行分析主键
     * @return 结果
     */
    @Override
    public int deletePreMuAnalysisPolicyImpleByBaseId(String baseId)
    {
        return preMuAnalysisPolicyImpleMapper.deletePreMuAnalysisPolicyImpleByBaseId(baseId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importTemplateData(MultipartFile file) {
        if(file.isEmpty()){
            return AjaxResult.warn("没有找到要上传的文件");
        }
        try{
            ExcelUtil<PreMuAnalysisPolicyImple> util = new ExcelUtil<PreMuAnalysisPolicyImple>(PreMuAnalysisPolicyImple.class);
            List<PreMuAnalysisPolicyImple> xlsxList = util.importExcel(file.getInputStream(),1);

            List<PreMuAnalysisPolicyImple> list = new ArrayList<>();

            for(PreMuAnalysisPolicyImple p : xlsxList){
                p.setBaseId(IdUtil.simpleUUID());
                p.setBaseCreateBy(SecurityUtils.getUserId());
                p.setBaseUpdateBy(SecurityUtils.getUserId());
                p.setBaseCreateTime(DateUtils.getNowDate());
                p.setBaseUpdateTime(DateUtils.getNowDate());

                list.add(p);

                if(list.size() > 100){
                    preMuAnalysisPolicyImpleMapper.batchInsertAnalysisPolicyImple(list);
                    list.clear();
                }
            }

            if(!list.isEmpty()){
                preMuAnalysisPolicyImpleMapper.batchInsertAnalysisPolicyImple(list);
                list.clear();
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("导入失败");
        }
        return AjaxResult.success("导入成功");
    }

    /**
     * 查询报告
     *
     * @param params
     * @return
     */
    @Override
    public AjaxResult queryBgDetailCount(PreMuAnalysisPolicyImple params) {

        if(StringUtils.isBlank(params.getProvince()) ||
                StringUtils.isBlank(params.getCity()) ||
                StringUtils.isBlank(params.getCounty()) ||
                StringUtils.isBlank(params.getReleaseYear())

        ){
            return AjaxResult.warn("请选择年份或行政区");
        }

        //查询本年度执行政策数量
        PreMuPolicyAnisVo currentYearPolicyExecCountMap = preMuAnalysisPolicyImpleMapper.selectCurrentYearPolicyExecCount(params);
        if(currentYearPolicyExecCountMap != null){
            BigDecimal mnqyzs = currentYearPolicyExecCountMap.getMnqyzs();
            BigDecimal zxqysl = currentYearPolicyExecCountMap.getZxqysl();

            if(mnqyzs.compareTo(BigDecimal.ZERO) == 0){
                currentYearPolicyExecCountMap.setZxl(null);
            }else{
                BigDecimal zxlBigDecimal = zxqysl.divide(mnqyzs, 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
                currentYearPolicyExecCountMap.setZxl(zxlBigDecimal);
            }
        }
        return AjaxResult.success(currentYearPolicyExecCountMap);
    }

    /**
     * 查谒正向反向激励的占比
     *
     * @param params
     * @return
     */
    @Override
    public AjaxResult queryZfjl(PreMuAnalysisPolicyImple params) {
        //查询正向激励
        params.setPolicyType("正向激励");
        Map zsJlMap = preMuAnalysisPolicyImpleMapper.queryZfjl(params);
        params.setPolicyType("反向倒逼");
        Map fxJlMap = preMuAnalysisPolicyImpleMapper.queryZfjl(params);

        Map<String,Object> resultMap = new HashMap<>(16);
        resultMap.put("zx",zsJlMap);
        resultMap.put("fx",fxJlMap);

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult queryCbhzcZzt(PreMuAnalysisPolicyImple params) {
        List<PreMuAnalysisPolicyImpleUnExecVo> preMuAnalysisPolicyImpleUnExecVo = preMuAnalysisPolicyImpleMapper.queryCbhzcZzt(params);

        List<String> xAxis = new ArrayList<>();
        List<String> unExecAxis = new ArrayList<>();
        List<String> execAxis = new ArrayList<>();

        for(PreMuAnalysisPolicyImpleUnExecVo t : preMuAnalysisPolicyImpleUnExecVo){
            String policyTypeSub = t.getTitle();
            BigDecimal unexec = t.getUnexec();
            BigDecimal execCount = t.getExecCount();

            xAxis.add(policyTypeSub);
            unExecAxis.add(unexec.toString());
            execAxis.add(execCount.toString());
        }

        Map<String,Object> resultMap = new HashMap<>(16);
        resultMap.put("xAxis",xAxis);
        resultMap.put("unExecAxis",unExecAxis);
        resultMap.put("execAxis",execAxis);
        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult queryReleaseDept(PreMuAnalysisPolicyImple params) {
        List<PreMuAnalysisPolicyImpleUnExecVo> preMuAnalysisPolicyImpleUnExecVo = preMuAnalysisPolicyImpleMapper.queryReleaseDept(params);

        List<String> xAxis = new ArrayList<>();
        List<String> unExecAxis = new ArrayList<>();
        List<String> execAxis = new ArrayList<>();

        for(PreMuAnalysisPolicyImpleUnExecVo t : preMuAnalysisPolicyImpleUnExecVo){
            String policyTypeSub = t.getTitle();
            BigDecimal unexec = t.getUnexec();
            BigDecimal execCount = t.getExecCount();

            xAxis.add(policyTypeSub);
            unExecAxis.add(unexec == null ? BigDecimal.ZERO.toString() : unexec.toString());
            execAxis.add(execCount == null ? BigDecimal.ZERO.toString() : execCount.toString());
        }

        Map<String,Object> resultMap = new HashMap<>(16);
        resultMap.put("xAxis",xAxis);
        resultMap.put("unExecAxis",unExecAxis);
        resultMap.put("execAxis",execAxis);
        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult queryCountyPolicyDetailInfo(PreMuAnalysisPolicyImple params) {
        List<PreMuAnalysisPolicyImple> r = preMuAnalysisPolicyImpleMapper.queryCountyPolicyDetailInfo(params);
        for(PreMuAnalysisPolicyImple temp : r){
            String execCount = temp.getExecCount();
            String simulationCount = temp.getSimulationCount();

            if(StringUtils.isBlank(simulationCount) || StringUtils.isBlank(execCount)){
                temp.setWcl("-");
                temp.setExecValue("-");
                temp.setExecCount("-");
            }else{
                BigDecimal execCountBigDec = new BigDecimal(execCount);
                BigDecimal simulationCountBigDec = new BigDecimal(simulationCount);

                if(simulationCountBigDec.compareTo(BigDecimal.ZERO) == 0){
                    temp.setWcl("-");
                    temp.setExecValue("-");
                    temp.setExecCount("-");
                }else{
                    BigDecimal multiply = execCountBigDec.divide(simulationCountBigDec, 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
                    temp.setWcl(multiply.toString());
                }
            }
        }
        return AjaxResult.success(r);
    }

    @Override
    public AjaxResult selectYdWz(PreMuAnalysisPolicyImple params) {
        List<PreMuAnalysisPolicyImple> r =  preMuAnalysisPolicyImpleMapper.selectYdWz(params);

        StringBuilder errorStr = new StringBuilder();
        StringBuilder overviewStr = new StringBuilder();
        StringBuilder oremarktr = new StringBuilder();

        for(int i =0;i<r.size();i++){
            PreMuAnalysisPolicyImple temp = r.get(i);
            if(i == 0){
                errorStr.append("<h1>").append(temp.getPolicyName()).append("</h1>").append("</br>");
                overviewStr.append("<h1>").append(temp.getPolicyName()).append("</h1>").append("</br>");
                oremarktr.append("<h1>").append(temp.getPolicyName()).append("</h1>").append("</br>");
            }
            errorStr.append(temp.getOverviewPolicyError()).append("</br>");
            overviewStr.append(temp.getOverviewPolicyJy()).append("</br>");
            oremarktr.append(temp.getRemark()).append("</br>");
        }

        Map<String,String> resultMap  = new HashMap<>(16);
        resultMap.put("jy",overviewStr.toString());
        resultMap.put("remark",oremarktr.toString());
        resultMap.put("error",errorStr.toString());
        return AjaxResult.success(resultMap);
    }
}